import axios from 'axios'

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || ''
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

const config = {
  baseURL: process.env.baseURL || process.env.apiUrl || '/api'
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
}

const _axios = axios.create(config)

// Add a response interceptor
_axios.interceptors.response.use(
  function({ data }) {
    var error
    if (data !== undefined && data.ret !== undefined) {
      if (data.ret >= 200 && data.ret < 400) {
        // 正确响应
        return data.data
      } else {
        // 一般错误
        error = data
      }
    } else {
      // 状态码200，但是没有ret说明后端框架加载失败
      error = {
        ret: 500,
        msg: '服务器无效'
      }
    }
    return Promise.reject(error)
    // return response
  },
  function({ response: { data }}) {
    var error
    if (data !== undefined && data.ret !== undefined) {
      error = data
    } else {
      // 状态码200，但是没有ret说明后端框架加载失败
      error = {
        ret: 500,
        msg: '服务器无效'
      }
    }
    return Promise.reject(error)
  }
)

export default _axios
